package com.icloud.cer.rest.common;

import java.util.Locale;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.msg.EncryptHandler;


public class ContextHolder {
	private static final Logger log = LoggerFactory.getLogger(EncryptHandler.class);
	
	static ThreadLocal<RequestContext> requestContext = new ThreadLocal<RequestContext>();
	
	public static Locale getSessionLocale() {
		// Locale locale = null;
		SessionContext session = getSessionContext();
		if (session == null)
			return Locale.getDefault();
		Locale l = session.getLocale();
		if (l == null)
			return Locale.getDefault();
		return l;
	}
	
	public static void initRequest(HttpServletRequest request, ServletResponse response) {
        requestContext.set(new RequestContext(request, response));
    }
	

	public static SessionContext getSessionContext() {
		RequestContext reqContext = requestContext.get();
		if (reqContext == null) {
			return null;
		}
		HttpSession session = reqContext.getSession(false);
		if (session == null) {
			return null;
		}
		SessionContext sessionContext = new SessionContext(session);
		sessionContext.setLocale(reqContext.getLocale());
		return sessionContext;
	}
	
	public static void requestClear() {
		requestContext.set(null);// context中的值等待线程结束自动垃圾回收
		//log.info("RequestContext is cleared.");
	}

}
